<template>
    <div ref="playerPEl" id="player-parent" class="video-tem"
        :style="{ height: isAuto ? 'auto' : 'calc(100vh - 100px)' }">
        <div ref="playerEl" id="player-el" class="" :style="divStyle"></div>
    </div>
</template>

<script setup lang='ts'>
import { indexOf, once } from 'underscore';
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncCreatedWatchVideo, asyncgetvideoInfo, asyncselectWhitepoint, jilurizhi } from '../../../api';
import { Storekey } from "../../../interface";
import Alymodel from '../../../mysql_interface/model';
import { delay, videoDimensions } from '../../../util/time';
interface IAVideoMeta {
    VideoId: string;
    Title: string;
    Duration: number;
    CoverURL: string;
    Status: string;
}
interface IvideoList {
    RequestId: string;
    VideoMeta: IAVideoMeta;
    PlayAuth: string;
}

type P = {
    lessionId: number | undefined;
    question: Alymodel.Ivideoquestion[];
    course: Alymodel.IMcourse;
};
const p = defineProps<P>()

const store = useStore(Storekey)
const route = useRoute()
const router = useRouter()
// 当前登录用户
const user = computed(() => {
    return store.state.user;
});
const teamId = computed(() => {
    return Number(user.value?.teamid);
});

watch(() => p.lessionId, async (e) => {
    start()
})

// 销毁
onBeforeUnmount(() => {
    recordLog()
    document.removeEventListener("keydown", playing, false);
    window.onresize = () => { };
    window.player?.dispose();
    window.player = undefined
    window.addEventListener('beforeunload', () => { });
    window.clearInterval(timerID.value)
})

onMounted(async () => {
    await start()
    window.onresize = () => {
        onResize()
    };
})

const videoInfo = ref<IvideoList>()
const whites = ref<Alymodel.Iwhitepoint[]>([]);

const logTime = ref(Date.now())
const isUseLogTime = ref(false)
const timerID = ref(0)

const playerPEl = ref<HTMLDivElement>();
const playerEl = ref<HTMLDivElement>();
const isAuto = ref(false)
const divStyle = ref()

async function start() {
    // 获取数据
    const whitesRet = await asyncselectWhitepoint({ lid: p.lessionId });
    whites.value = whitesRet as Alymodel.Iwhitepoint[]
    const ret = await asyncgetvideoInfo({ lid: p.lessionId });
    videoInfo.value = ret as IvideoList
    // 键盘控制：快进、后退、暂停
    document.addEventListener("keydown", playing, false);
    // 
    window.addEventListener('beforeunload', (event) => {
        if (isUseLogTime.value) {
            watchvideo(p, Math.floor((Date.now() - logTime.value) / 1000))
        }
    });
}
watch(() => videoInfo.value, async (e) => {
    if (e) {
        ended()
        if (window.player != null) {
            window.player.dispose();
        }
        // 播放器
        initPlayer(e?.VideoMeta?.VideoId, e?.VideoMeta?.CoverURL, e?.PlayAuth)
    }
}, { immediate: true })

function getwhite() {
    // setiswhites(true);
    const arr = [];
    // 定位快速搭建的位置
    for (let v of whites.value) {
        arr.push({
            offset: v.starttime,
            text: v.miaoshu,
        });
    }
    return arr;
}
async function initPlayer(vid: string, cover: any, playauth: any) {
    if (document.getElementById("player-con") === null) {
        let playerDomWrap = playerPEl.value;
        let playerDom = document.createElement("div");
        playerDom.setAttribute("id", "player-con");
        playerDomWrap?.appendChild(playerDom);
        //视频下方添加小div
        let bar = document.createElement("div");
        bar.setAttribute("id", "barcontrol");
        playerDom.appendChild(bar);
        isAuto.value = true;
    }
    const progressMarkers = getwhite();
    let height = (document.getElementById("player-parent") as any).offsetWidth * 0.52 - 20;
    height = height > 850 ? 850 : height;
    let cfg = {
        id: "player-con",
        width: "100%",
        height: height + "px",
        autoplay: true, // 自动播放
        language: "zh-cn",
        preload: false,
        isLive: false,
        progressMarkers: progressMarkers,
        cover: cover,
        playauth: playauth,
        vid: vid,
        encryptType: 1,
        controlBarVisibility: "always",
        playsinline: true,
        useH5Prism: true,
        enableSystemMenu: true,
        keyShortCuts: true,
        defaultDefinition: 'HD',
    };

    const Aliplayer = window.Aliplayer;
    window.player = new Aliplayer(cfg);

    window.player.on("ready", ready);
    window.player.on("play", play);
    window.player.on("pause", pause);
    window.player.on("ended", ended);
    window.player.on("timeupdate", timeupdate);
    window.player.on("completeSeek", completeSeek);
    window.player.on("playing", () => {
        isUseLogTime.value = true;
    });
    await delay(100);

    let video = document.getElementsByTagName("video")[0];
    video.addEventListener("click", playerControl, false);
}
// 控制
function playerControl() {
    const status = window.player?.getStatus()
    console.log("playerControl", status)
    if (status === "init") {
        window.player?.play();
    }
    if (status === "loading") {
        window.player?.play();
    }
    if (status === "ready") {
        window.player?.pause();
    }
    if (status === "playing") {
        window.player?.pause();
    }
    if (status === "pause") {
        window.player?.play();
    }
}
// 
function playing(e: KeyboardEvent) {
    const timeStep = 5
    if (e.code === "Space") {
        playerControl();
    } else if (e.code === "ArrowRight") {
        let currentTime = Math.ceil(window.player?.getCurrentTime());
        window.player?.seek((currentTime += timeStep));
    } else if (e.code === "ArrowLeft") {
        let currentTime = Math.ceil(window.player?.getCurrentTime());
        window.player?.seek((currentTime -= timeStep));
    }
}
function ready() {
    track()
}
const play = () => {
    logTime.value = Date.now();
    isUseLogTime.value = true;
    once(_play)()
}
// Watermark
function _play() {
    const text = `学员（${user.value?.ID}）正在学习`;
    if (timerID.value) return;
    let l = 1;
    let t = 1;

    const playerparent = document.querySelector<HTMLDivElement>("#player-con");
    const data = playerparent?.querySelector<HTMLDivElement>("#player-el");
    if (!data && playerEl.value) {
        playerparent?.appendChild(playerEl.value);
    }
    const el = document.querySelector<HTMLDivElement>("#player-el");
    if (el) {
        el.innerHTML = text;
        el.style.textAlign = "center";
        el.style.width = "200px";
        el.style.height = "20px";
        el.style.color = "#fff";
        el.style.position = "absolute";
        el.style.zIndex = "999";
        el.style.opacity = "0.5";
        el.style.filter = "alpha(opacity=60)";
        el.style.textShadow = "0 0 0.2em #000";
        el.style.display = "block";
    }
    const moveStep = 1
    timerID.value = window.setInterval(() => {
        if (el) {
            const left = parseInt(el?.style.left || "0") + l;
            const top = parseInt(el?.style.top || "0") + t;
            el.style.top = top + "px";
            el.style.left = left + "px";
            el.innerHTML = text;
            if (playerparent && left > playerparent.offsetWidth - 200) {
                l = -moveStep;
            }
            if (left < 0) { l = moveStep; }
            if (playerparent && top > playerparent?.offsetHeight - 20) {
                t = -moveStep;
            }
            if (top < 0) { t = moveStep; }
        }
    }, 20);
}

// 暂停播放
function pause() {
    recordLog()
    track()
}
// 结束 Web播放器支持通过设置rePlay属性或监听ended事件实现循环播放
function ended() {
    recordLog()
    track()
}
// 
function recordLog() {
    if (p.course && isUseLogTime.value) {
        watchvideo(p, Math.floor((Date.now() - logTime.value) / 1000))
    }
    isUseLogTime.value = false;
}
function track() {
    if (p.course && isUseLogTime.value) {
        const arr: any = [];
        arr[0] = ["type", "video"];
        arr[1] = ["isended", true];
        arr[2] = ["courseid", p.course.ID];
        arr[3] = ["coursename", p.course.name];
        arr[4] = ["watchtime", Date.now() - logTime.value];
        jilurizhi(arr);
    }
}

// 记录观看时长  time单位s
function watchvideo(p: P, time: number) {
    const proportion = Math.floor(time / window.player.getDuration() * 100)
    if (proportion) {
        asyncCreatedWatchVideo({
            courseid: p.course.ID,
            time,
            proportion
        })
    }
}

function timeupdate() {
    if (p.question.length) {
        // 获取当前视频时间
        let currentTime = Math.ceil(window.player.getCurrentTime());
        let arr = [];
        for (let v of p.question) {
            arr.push(v.time);
        }
        // 判断是否在暂停时间内
        let index = indexOf(arr, currentTime);
        if (index != -1) {
            // setopenWT(currentTime);
            // setdangqian(index);
        }
    }
}
function completeSeek() {
    // setopenWT(null);
}

async function onResize() {
    const v = document.querySelectorAll<HTMLVideoElement>("#video")[0];
    if (v) {
        let { width, height } = videoDimensions(v);
        if (width < 25) {
            await delay(300);
        }
        width = videoDimensions(v).width;
        height = videoDimensions(v).height;
        let a = v.offsetHeight;
        let b = (a - height) / 2;
        divStyle.value = {
            width: `${width}px`,
            height: `${height}px`,
            margin: "20px auto",
            top: `${b}px`,
        };
    }
}
</script>

<style scoped></style>
<style>
.prism-player .prism-big-play-btn {
    border: 6px solid rgba(70, 131, 250, .8);
    border-radius: 50%;
}

.prism-player .prism-big-play-btn .outter {
    border: none;
}
</style>